package com.hzmw.beetldemo.server;

import com.hzmw.beetldemo.dao.mapper.TableMapper;
import com.hzmw.beetldemo.dto.EntityOutDto;
import com.hzmw.beetldemo.dto.ParameterDto;
import com.hzmw.beetldemo.dto.TableColumnDto;
import com.hzmw.beetldemo.util.GeneratorUtils;

import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Hzmw
 * @create 2019-01-18 14:55
 * @email mengwei.zhao@nvrchina.com.cn
 * @description
 */
@Service
public class CodeService {

    @Autowired(required = false)
    private TableMapper tableMapper;
    @Autowired(required = false)
    private GroupTemplate groupTemplate;

    public void generate(ParameterDto dto) throws IOException {
        //1.数据表处理
        List<TableColumnDto> columnDtos = processTable(dto);
        //2.数据格式封装
        EntityOutDto outDto = new EntityOutDto();
        outDto.setTableName(dto.getTableName());
        outDto.setChName(dto.getChName());
        outDto.setEnNameBigFirst(GeneratorUtils.firstLetterToUpper(dto.getEnName()));
        outDto.setTablePropertyList(columnDtos);

        //模板路径
        Template pageTemplate = groupTemplate.getTemplate("Entity.java.btl");
        //Beetl方法
        groupTemplate.registerFunctionPackage("tool", new GeneratorUtils());
        //数据绑定
        pageTemplate.binding("context", outDto);
        // 生成实体类所在的路径
        String entityPath = "F:/codeGenerator/";
        //文件输出
        File file = new File(entityPath + outDto.getEnNameBigFirst() + ".entity");
        File parentFile = file.getParentFile();
        if (null != parentFile && !parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            pageTemplate.renderTo(new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private List<TableColumnDto> processTable(ParameterDto dto) {
        //数据表名
        String tableName = dto.getTableName();
        TableColumnDto query = new TableColumnDto();
        query.setName(tableName);
        //1.通过表名获取所有的字段，以及commit等信息
        List<TableColumnDto> columnDtos = tableMapper.findList(dto.getTableName());
        if (columnDtos.size() == 0) {
            return null;
        }
        //2.数据库的字段类型转换为java中的数据类型
        columnDtos = columnDtos.stream().peek(tableColumnDto -> {
            tableColumnDto.setJavaName(GeneratorUtils.firstLetterToLower(GeneratorUtils.toCamelCase(tableColumnDto.getName())));
            tableColumnDto.setJavaType(GeneratorUtils.jdbcToJavaType(tableColumnDto.getJdbcType()));
        }).collect(Collectors.toList());
        return columnDtos;
    }
}
